﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom.Compiler;
using System.Diagnostics;
using Microsoft.CSharp;
using System.Reflection;

namespace classGen {
    public static class libraryHelper {
        public static void GenLib(string filename) {

            string FooSourcHeader = @"
                   using System;
                   using System.Reflection;
                   [assembly: AssemblyVersion(""0.1.0.0"")]
                   class Foo {
                      static public void Print()
                      {";
            string FooSourceFooter = @"
                      }
                   }";

            string myPrint = FooSourcHeader
                           + @"System.Windows.Forms.MessageBox.Show(""Hi"");"
                           + FooSourceFooter;

            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = false;
            parameters.OutputAssembly = filename;
            
            parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, myPrint);
            if (results.Errors.Count == 0) {
                System.Windows.Forms.MessageBox.Show("Success");
            } else {
                string temp = null;
                for (int i = 0; i < results.Errors.Count; i++) {
                    temp += results.Errors[i].ErrorText + Environment.NewLine;
                }
                System.Windows.Forms.MessageBox.Show("Errors:"+temp);
            }
        }

        public static void ExecuteDLL(string filename){
            var dll = Assembly.LoadFile(filename);
            Type t = dll.GetType("Foo");
            try {
                t.GetMethod("Print").Invoke(null, null);
            } catch (Exception ex) {
                System.Windows.Forms.MessageBox.Show(ex.Message+Environment.NewLine+ex.StackTrace);
            }
        }

    }
}
